<template>
	<ul class="list">
		<li
		class="item"
		v-for="item of letters"
		:key="item"
		:ref="item"
		@click="handleLetterClick"
		@touchstart.prevent="handleTouchStart"
		@touchmove="handleTouchMove"
		@touchend="handleTouchEnd"
		>
			{{item}}
		</li>
	</ul>
</template>

<script>
export default{
	name: 'CityAlphabet',
	props: {
		cities: Object,
	},
	computed: {
		letters () {
			const letters = []
			for (let i in this.cities) {
				letters.push(i)
			}
			return letters  //返回值是个数组：['A','B','C',,,]
		}
	},
	data () {
		return {
			touchStatus: false , //touch事件发生的标识位
			startY: 0,
			timer: null,
		}
	},
	updated () {
		this.startY = this.$refs['A'][0].offsetTop //获取A元素距离上层控件/city-alphabet顶部的高度
	},
	methods: {
		//实现Alphabet组件与List非父子组件之间的通信，需要父组件转为两者中转
		handleLetterClick (e) {
			console.log('您点击的字符是：',e.target.innerText);
			this.$emit('change', e.target.innerText); //兄弟组件Alpabet发送change，并传入参数e.target.innerText，需要在父组件City中监听该事件。City组件监听change事件，绑定方法。City接收参数letter，转化给List组件。letter传递给List
		},
		handleTouchStart () {
			this.touchStatus = true
		},
		handleTouchMove (e) {
			if(this.touchStatus) {
				if(this.timer) {
					clearTimeout(this.timer);
				}
				//触摸事件16ms时间监听截流,等待16ms执行第二次触摸事件
				this.timer =setTimeout(() =>{
					const touchY = e.touches[0].clientY - 79 //header部分高度是79px，获取触摸的元素距离APP顶部的高度
					const index = Math.floor((touchY - this.startY)/20)  //字母的下标index，每个字母高20px
					// console.log('触摸的字母下标：',index);
					if(index>=0 && index<this.letters.length){
						console.log('您触摸的字符是：',this.letters[index]);
						this.$emit('change', this.letters[index])
						//兄弟组件Alphabet发送change，并传入参数this.letters[index]
					}
				}, 8)
			}
		},
		handleTouchEnd () {
			this.touchStatus = false
		}
	}
}
</script>

<style lang="stylus" scoped>
	@import '~@/assets/styles/varibles.styl'
	.list
		display: flex
		flex-direction: column
		justify-content: center //垂直方向居中
		position: absolute
		top: 1.58rem  //显现header部分，保持对齐
		right: 0
		bottom: 0
		width: .4rem
		// background: $bgColor
		.item
			color: $bgColor
			line-height: .4rem
			text-align: center
</style>
